package org.axe.jetty;

import org.axe.DispatcherServlet;
import org.axe.jetty.config.JettyConfig;
import org.axe.jetty.config.JettyServletFilter;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.ssl.SslContextFactory;

public final class AxeStartWeb {
	/**
	 * 带参数启动jetty
	 * @param filterList 过滤器的链
	 * @throws Exception 
	 */
	public static void startServer(JettyConfig config) throws Exception{
		//启动jetty
    	Server server = null;
    	if(StringUtil.isEmpty(config.getSslKeyPath())) {
    		server = new Server(config.getServerPort());
    	}else {
    		server = new Server();
    		
    		//设置SSL
    		SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
    		if(config.getSslKeyPath().endsWith(".p12")) {
    			sslContextFactory.setKeyStoreType("PKCS12");
    		}else {
    			throw new Exception("unsupported ssl key type");
    		}
    		String password = config.getSslPassword() == null?"":config.getSslPassword();
    		sslContextFactory.setKeyStorePath(config.getSslKeyPath());
    		sslContextFactory.setTrustStorePath(config.getSslKeyPath());
    		sslContextFactory.setKeyStorePassword(password);
    		sslContextFactory.setKeyManagerPassword(password);
    		
            HttpConfiguration https = new HttpConfiguration();
            https.setSecureScheme("https");
        	ServerConnector httpsConnector = new ServerConnector(server,new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https));
        	httpsConnector.setPort(config.getServerPort());
        	server.addConnector(httpsConnector);
    	}
        ServletContextHandler context = new ServletContextHandler();
        //设置上下文地址
        context.setContextPath("/");
        server.setHandler(context);
        
        //axe servlet
        ServletHolder axe = new ServletHolder(DispatcherServlet.class);
        axe.setInitOrder(1);//启动时加载
        context.addServlet(axe, "/*");
        
        //cross filter
        if(config.getFilterList() != null && config.getFilterList().size() > 0){
        	for(JettyServletFilter filter:config.getFilterList()){
        		context.addFilter(filter.getHolder(), filter.getPathSpec(), filter.getDispatches());
        	}
        }
        
        //启动
        server.start(); 
        server.join();
	}
	
}
